// 获取页面信息
const pageInfo = getCurrentPages()
Page({
  onLoad(options) {
    const app = getApp()
    this.setData({ ...app.profileInfo })

  },
  // 获取用户昵称
  getUserNikeName(ev) {
    this.updateUserNikeName(ev.detail.value)
  },
  // 更新昵称
  async updateUserNikeName(nickName) {
    if (nickName === '') return
    const { code, data } = await wx.http.put('/userInfo', { nickName })
    if (code !== 10000) return wx.utils.toast()
    pageInfo[0].setData({ nickName })
    getApp().profileInfo.nickName = nickName
  },
  // 获取头像
  getUserAvatar(ev) {
    this.updateUserAvatar(ev.detail.avatarUrl)

  },
  // 更新头像
  updateUserAvatar(avatarUrl) {
    wx.uploadFile({
      url: wx.http.baseURL + '/upload',
      filePath: avatarUrl,
      name: 'file',
      header: {
        Authorization: 'Bearer ' + getApp().token
      },
      formData: {
        type: 'avatar'
      },
      success: (result) => {
        const data = JSON.parse(result.data)
        if (data.code !== 10000) return wx.utils.toast()
        pageInfo[0].setData({ avatar: data.data.url })
        this.setData({ avatar: data.data.url })
        getApp().profileInfo.avatar = data.data.url

      }
    })
  }
})